package org.wiztools.portlet.arbitrarytext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.log4j.Logger;

public class ArbitraryTextPortlet extends GenericPortlet {

    private static final  Logger LOG = Logger.getLogger(ArbitraryTextPortlet.class);
    private static final String VIEW = "/view.jsp";

    @Override
    public void doView( RenderRequest request, RenderResponse response )
        throws PortletException, IOException {

        List<String> errors = new ArrayList<String>();
        
        PortletPreferences prefs = request.getPreferences();
        String arbitraryText = prefs.getValue("arbitrary-text", "");
        LOG.info("arbitrary-text: " + arbitraryText);

        if(arbitraryText.trim().equals("")){
            errors.add("Portlet not configured. Please contact Administrator!");
        }
        else{
            request.setAttribute("arbitraryText", arbitraryText);
        }

        if(errors.size() > 0){
            request.setAttribute("errors", errors);
        }
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(VIEW);
        rd.include(request, response);
    }

    @Override
    public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {

        PortletPreferences prefs = request.getPreferences();

        String arbitraryText = prefs.getValue("arbitrary-text", "");

        request.setAttribute("arbitraryText", arbitraryText);
        getPortletContext().getRequestDispatcher("/edit.jsp").include(request, response);
    }

    @Override
    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
        String arbitraryText = request.getParameter("arbitraryText");

        LOG.info("arbitraryText (from submit): " + arbitraryText);
        
        PortletPreferences prefs = request.getPreferences();
        prefs.setValue("arbitrary-text", ( arbitraryText == null ) ? "" : arbitraryText);
        prefs.store();

        request.setAttribute("message", "Text snippet stored!");
    }
}
